package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.annotations.Until;
import com.itheima.reggie.commen.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.until.Sample;
import com.itheima.reggie.until.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    //获取验证码
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) throws Exception {
        String phone = user.getPhone();

        if (StringUtils.isNotEmpty(phone)){
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            System.out.println("code========"+code);
            //Sample.getCheckWord(phone,code);
           /* //保存手机号和验证码到session里面
            session.setAttribute(phone,code);*/

            //将验证码保存到redis中,设置有效期5分钟
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.success("发送成功");
        }
       return R.error("发送失败");
    }

    //登录
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String,String> map, HttpSession session){
        String phone = map.get("phone");
        String code = map.get("code");

//        Object codeInsSession = session.getAttribute(phone);

        Object codeInRedis = redisTemplate.opsForValue().get(phone);
        if (codeInRedis!=null&&codeInRedis.equals(code)){
            //检查是否为新用户,为新用户的话进行保存
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user==null){
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            //保存session信息
            session.setAttribute("employee",user.getId());
            //登录成功后清除redis中保存的验证码
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败，请检查手机号和验证码");
    }
}
